﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Reflection;
using System.Collections.Generic;

namespace Caramel.Web.Mvc.Validation
{
	public class FluentModelValidatorContainer : ModelValidatorContainer
	{
		private readonly IList<Type> _types = new List<Type>();
		private readonly IList<Assembly> _assemblies = new List<Assembly>();

		public FluentModelValidatorContainer Add<T>()
		{
			this.Add(typeof(T));

			return this;
		}

		public FluentModelValidatorContainer Add(Type type)
		{
			_types.Add(type);

			return this;
		}

		public FluentModelValidatorContainer AddFromAssemblyOf<T>()
		{
			return this.AddFromAssembly(typeof(T).Assembly);
		}

		public FluentModelValidatorContainer AddFromAssembly(Assembly assembly)
		{
			_assemblies.Add(assembly);

			return this;
		}

		internal override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
		{
			var validatorTypes =
				_assemblies.
					SelectMany(
						a =>
						a.
							GetExportedTypes().
							Where(t => typeof(IClassValidator).IsAssignableFrom(t))
					);

			IClassValidator validator = null;

			if (metadata.ContainerType == null)
			{
				var validatorType =
					validatorTypes.
						Where(t => t.BaseType.GetGenericArguments().First() == metadata.ModelType).
						FirstOrDefault();

				if (validatorType != null)
				{
					validator = Activator.CreateInstance(validatorType) as IClassValidator;
				}
			}
			else if (metadata.ContainerType != null)
			{
				var containerValidatorType =
					validatorTypes.
						Where(t => t.BaseType.GetGenericArguments().First() == metadata.ContainerType).
						FirstOrDefault();

				if (containerValidatorType != null)
				{
					var classValidator = Activator.CreateInstance(containerValidatorType) as IClassValidator;

					//if (classValidator.Properties.ContainsKey(propertyName))
					//{
					//    metadata = classMetadata.Properties[propertyName] as IModelMetadata;
					//}
				}
			}

			if (validator != null)
			{
				
			}

			return new List<ModelValidator>();
		}
	}
}
